package wifiunion.com.notice.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.DeviceDialogCallBack;
import wifiunion.com.notice.MyNoticeListener;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.adapter.AddNoticeDeviceAdapter;
import wifiunion.com.notice.entity.DeviceInList;
import wifiunion.com.notice.entity.DeviceLocation;
import wifiunion.com.notice.entity.DeviceSelectSth;
import wifiunion.com.notice.entity.NoticeInfoList;
import wifiunion.com.notice.presenter.GetNoticeDeviceLoclistPresenter;
import wifiunion.com.notice.presenter.GetNoticeDevicelistPresenter;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.widget.AddNoticeGroupDeviceDialog;
import wifiunion.com.notice.widget.DeviceSelectSthDialog;
import wifiunion.com.notice.widget.LoadMoreFooterView;

/**
 * Created by Administrator on 2016/11/28.
 * 添加识别设备
 */

public class AddRecognitionDeviceFragment extends BaseFragment implements OnLoadMoreListener, OnRefreshListener, View.OnClickListener,NoticeContact.View {

    private View mMainView;
    private int pageType;
    private String noticeUuid;
    private TextView subTitle2;
    private String mAuthtoken;
    private IRecyclerView mRecyclerView;
    private TextView mDeviceLocContentTv;
    private LoadMoreFooterView mLoadMoreFooterView;
    private TextView mSubGroupTv;
    private EditText mSearchEdt;

    private Button mSearchBtn;
    private AddNoticeDeviceAdapter mAdataper;
    private List<DeviceInList> mData = new ArrayList<>();
    private int mType = 0;
    private String devicelocationUuid = "-1";
    private ArrayList<DeviceLocation> mLocSpinnerlist = new ArrayList<>();

    private GetNoticeDeviceLoclistPresenter mGetNoticeDeviceLoclistPresenter;
    private GetNoticeDevicelistPresenter mGetNoticeDevicelistPresenter;

    private DeviceSelectSthDialog mselectDialog;
    private int mPageNum = 1;

    private AddNoticeGroupDeviceDialog mAddNoticeGroupDeviceDialog;

    private TextView headDowntv;
    private TextView headUpTv;

    private ImageView ovaldeviceIv;
    private TextView titledeviceTv;

    private TextView groupDelTv;

    private Button searchBtn;
    private NoticeInfoList mNoticeInfoList;

    private LinearLayout sub_header_filter_layout2;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_addnoticedevicelist, container, false);

        Bundle bundle = getArguments();
        if(null != bundle)
        {
            pageType = bundle.getInt("pageType");
            if(pageType == 0)
            {
                noticeUuid = bundle.getString("noticeUuid");
            }else if(pageType ==1 || pageType  == 2)
            {
                mNoticeInfoList = (NoticeInfoList)bundle.getSerializable("notice");
                noticeUuid = mNoticeInfoList.getUuid();
            }

        }
        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, getActivity());
        initview();
        return mMainView;
    }

    public void initview() {

        ovaldeviceIv = (ImageView) mMainView.findViewById(R.id.oval_device_iv);
        ovaldeviceIv.setBackgroundResource(R.drawable.notice_mark_material_select);
        titledeviceTv = (TextView) mMainView.findViewById(R.id.title_device_tv);


        headUpTv  = (TextView) mMainView.findViewById(R.id.notice_head_up_tv);
        headUpTv.setOnClickListener(this);

        headDowntv  = (TextView) mMainView.findViewById(R.id.notice_head_down_tv);
        headDowntv.setOnClickListener(this);

        sub_header_filter_layout2 = (LinearLayout) mMainView.findViewById(R.id.sub_header_filter_layout2);
        sub_header_filter_layout2.setVisibility(View.GONE);

        groupDelTv = (TextView) mMainView.findViewById(R.id.group_del_tv);
        groupDelTv.setVisibility(View.GONE);

        searchBtn = (Button) mMainView.findViewById(R.id.search_btn);
        searchBtn.setOnClickListener(this);

        subTitle2 = (TextView) mMainView.findViewById(R.id.sub_header_filter_title2_tv);
        subTitle2.setText("设备位置");
        mRecyclerView = (IRecyclerView) mMainView.findViewById(R.id.notice_device_irecyclerView);
        mDeviceLocContentTv = (TextView) mMainView.findViewById(R.id.sub_header_filter_content2_tv);
        mDeviceLocContentTv.setOnClickListener(this);
        mDeviceLocContentTv.setText("全部");
        mLoadMoreFooterView = (LoadMoreFooterView) mRecyclerView.getLoadMoreFooterView();
        mSubGroupTv = (TextView) mMainView.findViewById(R.id.group_add_tv);
        mSubGroupTv.setText("添加识别设备");

        mSearchEdt = (EditText) mMainView.findViewById(R.id.search_edt);
        mSearchEdt.setVisibility(View.GONE);
        mSearchBtn = (Button) mMainView.findViewById(R.id.search_btn);
        mSearchBtn.setVisibility(View.GONE);
        refreshView(mType);
        mSearchBtn.setOnClickListener(this);
        mSubGroupTv.setOnClickListener(this);
        mRecyclerView.setOnLoadMoreListener(this);
        mRecyclerView.setOnRefreshListener(this);

        if(pageType == 1)
        {
            //查看模式
            mSubGroupTv.setEnabled(false);
        }
        else
        {
            //添加/编辑模式
            mSubGroupTv.setEnabled(true);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
//                    getFragmentManager().popBackStack();
                    getActivity().getSupportFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }



    @Override
    public void initData() {

        mLocSpinnerlist.clear();

        DeviceLocation all =   new DeviceLocation();
        all.setUuid("-1");
        all.setName("全部");
        mLocSpinnerlist.add(all);
        mGetNoticeDeviceLoclistPresenter.start();

        mData.clear();
        getNoticeList();


    }

    public void getNoticeList()
    {
        HashMap<String, Object> mParams = new HashMap<>();
        mParams.put("Authorization", mAuthtoken);
        mParams.put("uuid",noticeUuid);
        mParams.put("pageNum", String.valueOf(mPageNum));
        mParams.put("pageSize", String.valueOf(10));
        if(!"-1".equals(devicelocationUuid))
        {
            mParams.put("deviceLocationUuid", devicelocationUuid);
        }

        if (null != mSearchEdt.getText().toString() && mSearchEdt.getText().toString().length() > 0) {
            mParams.put("condition", mSearchEdt.getText().toString());
        } else {

        }
        mGetNoticeDevicelistPresenter.getNoticeDeviceList(mParams,0);
        mRecyclerView.setRefreshing(true);

    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mGetNoticeDeviceLoclistPresenter = new GetNoticeDeviceLoclistPresenter(getContext(),this);
        mGetNoticeDevicelistPresenter = new GetNoticeDevicelistPresenter(getContext(),this);

        initData();

    }


    private void refreshView(int type) {
        mAdataper = new AddNoticeDeviceAdapter(getActivity(), type, mData);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setIAdapter(mAdataper);
    }



    @Override
    public void onClick(View view) {

        int i = view.getId();
        if (i == R.id.sub_header_filter_content2_tv) {
            ArrayList<DeviceSelectSth> locdata = new ArrayList<DeviceSelectSth>();
            for (DeviceLocation deviceLocation : mLocSpinnerlist) {
                DeviceSelectSth dd = new DeviceSelectSth();
                dd.setSelected(false);
                dd.setName(deviceLocation.getName());
                locdata.add(dd);
            }

            mselectDialog = new DeviceSelectSthDialog(getContext(), locdata, mDeviceLocCallback);
            mselectDialog.setTitleMsg("选择设备位置");
            mselectDialog.show();


        } else if (i == R.id.group_add_tv) {
            mAddNoticeGroupDeviceDialog = new AddNoticeGroupDeviceDialog(getContext(), getActivity(), noticeUuid, mLocSpinnerlist, myListener, 0);
            mAddNoticeGroupDeviceDialog.setTitleMsg("添加识别设备");
            mAddNoticeGroupDeviceDialog.show();

        } else if (i == R.id.notice_head_up_tv) {
            getActivity().getSupportFragmentManager().popBackStack();


        } else if (i == R.id.notice_head_down_tv) {
            if (pageType == 0) {

                if (!mData.isEmpty()) {
                    AddNoticeTargetFragment atf = new AddNoticeTargetFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("noticeUuid", noticeUuid);
                    bundle.putInt("pageType", pageType);
                    atf.setArguments(bundle);
                    //跳转到添加设备页面
                    getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "45").addToBackStack(null).commit();
                } else {
                    Toast.makeText(getContext(), "请先添加识别设备", Toast.LENGTH_SHORT).show();
                }
            } else if (pageType == 1 || pageType == 2) {

                if (pageType == 2) {

                    if (!mData.isEmpty()) {
                        AddNoticeTargetFragment atf = new AddNoticeTargetFragment();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("notice", mNoticeInfoList);
                        bundle.putInt("pageType", pageType);
                        atf.setArguments(bundle);
                        //跳转到添加设备页面
                        getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "45").addToBackStack(null).commit();
                    } else {
                        Toast.makeText(getContext(), "请先添加识别设备", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    AddNoticeTargetFragment atf = new AddNoticeTargetFragment();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("notice", mNoticeInfoList);
                    bundle.putInt("pageType", pageType);
                    atf.setArguments(bundle);
                    //跳转到添加设备页面
                    getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "45").addToBackStack(null).commit();
                }

            }

        } else if (i == R.id.search_btn) {
            mData.clear();
            getNoticeList();


        }


    }

    //回调刷行列表
    private MyNoticeListener myListener = new MyNoticeListener(){
        @Override
        public void refreshData(final String text){

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    mAddNoticeGroupDeviceDialog.dismiss();


                    mData.clear();
                    mAdataper.notifyDataSetChanged();
                    mPageNum = 1;
                    getNoticeList();


                }
            });

        }

        @Override
        public void refreshCancelData(final String text) {

        }

        @Override
        public void onResponse(List<Object> data) {

        }

    };




    @Override
    public void onLoadMore() {
        if (mLoadMoreFooterView.canLoadMore() && mAdataper.getItemCount() > 0) {
            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.LOADING);

            mPageNum += 1;
            getNoticeList();
            mRecyclerView.setRefreshing(false);
        }
    }

    @Override
    public void onRefresh() {

        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        mData.clear();
        mAdataper.notifyDataSetChanged();
        mPageNum = 1;
        getNoticeList();
        mRecyclerView.setRefreshing(true);

    }

    /**
     * 位置对话框回调结果
     */
    private DeviceDialogCallBack mDeviceLocCallback = new DeviceDialogCallBack() {
        @Override
        public void updateList(ArrayList<DeviceSelectSth> data) {
            int position = -1;

            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).isSelected()) {
                    position = i;
                }
            }
            try {
                devicelocationUuid =  mLocSpinnerlist.get(position).getUuid();

                mDeviceLocContentTv.setText(mLocSpinnerlist.get(position).getName());
            } catch (Exception e) {
                devicelocationUuid = "-1";

                mDeviceLocContentTv.setText("全部");
            }
        }
    };


    @Override
    public void onProgress() {

    }

    @Override
    public void onError(Object obj) {

    }

    @Override
    public void onSuccess(Object obj) {

    }

    @Override
    public void getGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeListSuccess(Object obj) {

    }

    @Override
    public void getNotificationUserSuccess(Object obj) {

    }

    @Override
    public void getNotificationRelGroupList(Object obj) {

    }

    @Override
    public void getNoticeRelGroupMemberListSuccess(Object obj) {

    }

    @Override
    public void addNoticeSBDXSuccess(String noticeUuid) {

    }

    @Override
    public void addSBSDSuccess(Object obj) {

    }


    @Override
    public void onGetDeviceLocListSuccess(Object obj) {

        List<DeviceLocation> list = (List<DeviceLocation>) obj;
        mLocSpinnerlist.addAll(list);

    }

    @Override
    public void onGetDeviceListSuccess(final Object obj) {

        if(null != getActivity())
        {


            mData.addAll((List<DeviceInList>) obj);

            mAdataper.notifyDataSetChanged();
            mRecyclerView.setRefreshing(false);
            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);

        }

    }

    @Override
    public void onGetNoticeDeviceGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeDeviceSuccess(Object obj) {

    }

    @Override
    public void getTopGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeTargetListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetRelGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeTarGetDeviceSuccess(Object obj) {

    }

    @Override
    public void addNoticeDataSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeSuccess(Object obj) {

    }

    @Override
    public void addNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void addNoticeRelGroupSuccess(Object obj) {

    }

    @Override
    public void setNoticeFromSuccess(Object obj) {

    }

    @Override
    public void getNoticeDetailSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void setPresenter(BasePresenter tp) {

    }
}
